<?php
namespace jy_weishop_en;
defined('BY_JYA') or exit('error');
/*
	订单，V8打印机：58mm（32字符），V9：80mm（42字符）
	设置字体大小、居中及切纸、来单提示音：http://www.jinyunzn.com/manage/index.php?plugin=core&action=article.show&nosession=1&id=11（出处：进云手册）
*/
class printmsg extends \plugin{
	public function storeprint($sendcontent='',$order_id='',$is_pay=0,$daike=0,$printerid=0,$pluginname='',$ordergoods=array(),$isadd=false){
		$isprint=false;
		//打印内容：
		$order=pdo_get('jy_weishop_order',array('id'=>$order_id));
		if(!$ordergoods){
			$ordergoods=pdo_getall('jy_weishop_order_goods',array('orderid'=>$order_id));
		}
		if($ordergoods){
			$goodsstr=$this->getgoodsstr($ordergoods);
			$ordergoods=$goodsstr['ordergoods'];
			$goodsinfo=$goodsstr['goodsinfo'];
			$goodsinfonew=$goodsstr['goodsinfonew'];
		}
		$send_type=$this->send_types[$order['sendtype']];
		$selfinfo=pdo_get('jy_weishop_order_self',array('orderid'=>$order_id));
		if($order['sendtype']==1){
			$send_type=$order['is_peisong']!=1?'快递配送':'同城配送';
		}elseif($order['sendtype']==2){
			if($order['isdish']==1){
				$send_type='店内';
			}else{
				$send_type='自提/店内';
			}
		}elseif($order['sendtype']==3){
			if($order['isdish']==1){
				$send_type='预约';
			}else{
				$send_type='虚拟物品';
			}
			
		}
		$self_type='默认';
		$xiadanname=pdo_getcolumn('core_members',array('id'=>$order['mid']),'nickname');
		if($selfinfo){
			if($order['isdish']==1){
				if($order['sendtype']==2){
					if($selfinfo['type']==1){
						$self_type='店内就餐';
					}else{
						$self_type='打包带走';
					}
				}elseif($order['sendtype']==1){
					if($selfinfo['type']==1){
						$self_type='普通';
					}else{
						$self_type='普通';
					}
				}
			}
			$selfnumber=$selfinfo['number'];
			$nickname = $selfinfo['username'];
			$mobile = $selfinfo['mobile'];
			$address=$selfinfo['address'];
		}else{
			$mobile=pdo_getcolumn('core_members',array('id'=>$order['mid']),'mobile');		
			if($order['addressid']){
				$address=pdo_get('core_address',array('id'=>$order['addressid']),array('pcd','address','mobile','name'));			
				if($address){
					$nickname=$address && $address['name']?$address['name']:$xiadanname;
					$mobile=$address && $address['mobile']?$address['mobile']:$mobile;
					$address['pcd']=$address['pcd']?json_decode($address['pcd'],true):array();
					$address=$address['pcd']['province'].' '.$address['pcd']['city'].' '.$address['pcd']['district'].' '.$address['pcd']['street'].''.$address['address'];
				}
			}
		}
		$is_pays =array('0'=>'未支付','1'=>'已支付');
		$text = "<AM><S1>下单通知\n</S1></AM>";
		if($order['sendtype'] == 2){
			if($order['isdish']){
				if($order['tableid']){
					$table=pdo_get('jy_weishop_table',array('uniacid'=>$_SESSION['uniacid'],'id'=>$order['tableid']),array('title','group_id'));
					$grouptitle=pdo_getcolumn('jy_weishop_table_group',array('uniacid'=>$_SESSION['uniacid'],'id'=>$table['group_id']),'title');
					$tabletitle=$grouptitle.'-'.$table['title'];
					$text="<AM><S2>桌号:".$tabletitle."\n</S2></AM>";
				}else{
					$text="<AM><S2>取餐号\n</S2></AM>";
					$text.="<AM><S2>".$selfnumber."\n</S2></AM>";
				}
			}else{
				$text="<AM><S2>取货号\n</S2></AM>";
				$text.="<AM><S2>".$selfnumber."\n</S2></AM>";
			}
		}
		if($order['isdish']){
			$text .="【菜品详情】\n";
		}else{
			$text .="【商品详情】\n";
		}
		$textnew=$text;
		$textend ='';
		if($daike){
			$nickname = $selfinfo['username']?$selfinfo['username']:'代客下单';
		}
		$paytitle=($order['status']==1 && $order['ispay']!=1)?'货到付款':'线上支付';
		if(!$isadd){
			$textend ='商品合计:'.$order['goodsprice']."\n";
			if($order['level_de_price']>0){		
				$textend .='会员折扣:'.$order['level_de_price']."\n";
			}
			if($order['dispatchprice']>0){
				$textend .='运费:'.$order['dispatchprice']."\n";
			}
			if($order['enough_de_price']>0){
				$textend .='满额减:'.$order['enough_de_price']."\n";
			}
			if($order['coupon_de_price']>0){
				$textend .='优惠券减:'.$order['coupon_de_price']."\n";
			}
			$textend .='实收:'.$order['price']."\n";
			$textend .='下单时间:'.date('Y-m-d H:i:s',$order['createtime'])."\n";
			if(!$order['isdish']){
				$textend .='订单类型:'.$send_type.'-('.$self_type.")\n";		
				$textend .='是否支付:'.$is_pays[$order['ispay']].'-('.$paytitle.")\n";
				$textend .='下单人:'.$xiadanname."\n";
				$selfinfo['selftime']=$selfinfo['selftime']?date('Y-m-d H:i:s',$selfinfo['selftime']):'尽快配送';
				$selfinfo['selftime']=$selfinfo['out_time']?:$selfinfo['selftime'];
				if($order['sendtype']==1){//快递配送
					$textend .='收货人:'.$nickname."\n";
					$textend .='收货手机:'.$mobile."\n";
					$textend .='配送地址:'.$address."\n";
					$textend .="配送时间：".$selfinfo['selftime']."\n";
				}elseif($order['sendtype']==2){//自提/店内	
				}elseif($order['sendtype']==3){//虚拟商品
				}
			}
		}
		if($order['remark']){
			$textend .='备注:'.$order['remark']."\n";
		}
		$params=array('uniacid'=>$_SESSION['uniacid']);
		if($order['merchid']){
			$params['merchid']=$order['merchid'];
		}elseif($order['storeid']){
			$params['storeid']=array(0,$order['storeid']);
		}
		if($printerid){
			$printers=pdo_getall('jy_weishop_printer',array('id'=>$printerid,'uniacid'=>$_SESSION['uniacid']));
		}else{
			$printers=pdo_getall('jy_weishop_printer',$params);
		}
		foreach($printers as $p){
			if($p['goodstype']){
				if($p['goodstype']==1 && $p['goodspids']){
					//按商品分类打印
					$goods=array();
					foreach($ordergoods as $ov){
						if(strpos($p['goodspids'],';'.$ov['pcate'].';') !== false){
							$goods[]=$ov;
						}
					}
					$p['ordergoods']=$goods;
				}elseif($p['goodstype']==2){
					//指定商品打印
					$p['goods']=json_decode($p['goods'],true);
					$setgoods=';';
					foreach($p['goods'] as &$p){
						$setgoods .=$p['id'].';';
					}
					$goods=array();
					foreach($ordergoods as $ov){
						if(strpos($setgoods,';'.$ov['goodsid'].';') !== false){
							$goods[]=$ov;
						}
					}
					$p['ordergoods']=$goods;
				}
				$goodsstr=$this->getgoodsstr($p['ordergoods']);
				$goodsinfo=$goodsstr['goodsinfo'];
				$goodsinfonew=$goodsstr['goodsinfonew'];
			}
			$ordergoods=$p['ordergoods']?:$ordergoods;
			if(count($ordergoods)<1){
				continue;
			}
			//单商品打印
			if($p['tpl_type']==1){
				$pgoods=array();
				foreach($ordergoods as $ov){
					$pgoods[0]=$ov;
					$goodsstr=$this->getgoodsstr($pgoods,$tpl_type);
					$goodsinfo=$goodsstr['goodsinfo'];
					$goodsinfonew=$goodsstr['goodsinfonew'];
					$textinfo=array(
						'goodsinfo'=>$goodsinfo,
						'goodsinfonew'=>$goodsinfonew,
						'text'=>$text,
						'textnew'=>$textnew,
						'textend'=>$textend,
					);
					$this->toprint($p,$textinfo,$order,$daike);
				}
			}else{
				/*if($p['templateid']){
					$datas=$this->model('notice')->gettpl_data($order_id);
					$tpl=pdo_get('jy_weishop_printer_template',array('id'=>$p['templateid'],'uniacid'=>$_SESSION['uniacid']));
					$content=$tpl['print_top']."\n";
					$tpl['print_data']=json_decode($tpl['print_data'],true);
					foreach($tpl['print_data'] as $tv){
						$content .=$tv['value']."\n";
					}
					if($tpl['isqrcode']){
						$content .= "<AM><QR_T>QR_CODE</QR_T><QR_S>7</QR_S><QR_D>".$tpl['qrcode']."</QR_D></AM>";
					}
					$content=model('core/account')->replaceTemplate($content,$datas);
				}*/
				$textinfo=array(
					'goodsinfo'=>$goodsinfo,
					'goodsinfonew'=>$goodsinfonew,
					'text'=>$text,
					'textnew'=>$textnew,
					'textend'=>$textend,
				);
				$this->toprint($p,$textinfo,$order,$daike);
			}
			pdo_update('jy_weishop_order',array('isprint'=>1),array('id'=>$order_id,'uniacid'=>$_SESSION['uniacid']));
			$isprint=true;
		}
		return $isprint;
	}
	public function getgoodsstr($ordergoods,$tpl_type=0)
	{
			$str=$strnew = '';
			foreach($ordergoods as &$g){
				if(!$g['title']){
					$info=pdo_get('jy_weishop_goods',array('id'=>$g['goodsid']),array('title','pcate'));
					$g['title']=$info['title'];
					$g['pcate']=$info['pcate'];
				}
				$title0=cfc('tools')->substr($g['title'],0,10);
				if($g['optionid']){
						$str .=  $this->strlen_pad($title0,20)."\n";
						$money = $g['price'] * $g['total'];
						$str .= $this->strlen_pad('-['.$g['optiondata'].']',20);
						if($tpl_type){
							$str .= $this->strlen_pad('x'.$g['total'].'/份',5);
						}else{
							$str .= $this->strlen_pad('x'.$g['total'],5);
						}
						if(!$tpl_type){
							$str .= ''. number_format($money, 2) . "\n";
						}
						$strnew .= $this->strlen_pad($title0,30)."\n";
						$strnew .= $this->strlen_pad('-['.$g['optiondata'].']',30);
						if(!$tpl_type){
							$strnew .= '<AR>x'.$g['total'].'  '. number_format($money, 2) . "\n</AR>";
						}else{
							$strnew .= '<AR>x'.$g['total']."/份\n</AR>";
						}
				}else{
						$money = $g['price'] * $g['total'];
						$str .= $this->strlen_pad($title0,20);
						if($tpl_type){
							$str .= $this->strlen_pad('x'.$g['total'].'/份',5);
						}else{
							$str .= $this->strlen_pad($g['total'],5);
						}
						$str .= ''. number_format($money, 2) . "\n";
						$strnew .= $this->strlen_pad($title0,30);
						if(!$tpl_type){
							$strnew .= '<AR>'.$g['total'].'  '. number_format($money, 2) . "\n</AR>";
						}else{
							$strnew .= '<AR>x'.$g['total']."/份\n</AR>";
						}
				}
			}
			if($tpl_type){
				$goodsinfo='';
				$goodsinfonew='';
			}else{
				$goodsinfo=$this->strlen_pad('名称',20)."<AR>数量  单价\n</AR>";
				$goodsinfonew=$this->strlen_pad('名称',30)."<AR>数量  单价\n</AR>";
			}
			$goodsinfo .= $str;
			$goodsinfo .= "-------------------------------\n";
			$goodsinfonew .= $strnew;
			$goodsinfonew .= "------------------------------------------\n";
			return array('goodsinfo'=>$goodsinfo,'goodsinfonew'=>$goodsinfonew,'ordergoods'=>$ordergoods);
	}
	public function toprint($p,$textinfo=array(),$order=array(),$daike=0){
			$goodsinfo=$textinfo['goodsinfo'];
			$goodsinfonew=$textinfo['goodsinfonew'];
			$text=$textinfo['text'];
			$textnew=$textinfo['textnew'];
			$textend=$textinfo['textend'];
			$tpl_type=$p['tpl_type'];
			$textnew .="------------------------------------------\n";
			$textnew .=$goodsinfonew;
			$text .="-------------------------------\n";
			$text .=$goodsinfo;
			if(!$tpl_type){
				$text .=$textend;
				$textnew .=$textend;
			}
			//print_r($textnew);exit;
			if($p['type']==3){
				if($p['print_top']){
					$content = "<AM><S1>".$p['print_top']."\n</S1></AM>";
					$content .=$textnew;
				}else{
					$content=$textnew;
				}
			}elseif($p['type']==7){
				//飞蛾打印机
				if($p['print_top']){
					$content = "<CB>".$p['print_top']."\n</CB>";
					$content .=$text;
				}else{
					$content=$text;
				}
				$content=str_replace('\n','<BR>',$content);
				$content=str_replace('<AM><S1>','<BOLD>',$content);
				$content=str_replace('</S1></AM>','</BOLD>',$content);
				$content=str_replace('<AM><S2>','<BOLD>',$content);
				$content=str_replace('</S2></AM>','</BOLD>',$content);
				$content=str_replace('<AM><S3>','<CB>',$content);
				$content=str_replace('</S3></AM>','</CB>',$content);
				$content=str_replace('<BR></CB>','</CB><BR>',$content);
				$content=str_replace('<AR>','',$content);
				$content=str_replace('</AR>','',$content);
			}elseif($p['type']==8){
				//芯烨打印机
				if($p['print_top']){
					$content = "<CB>".$p['print_top']."</CB><BR>";
					$content .=$textnew;
				}else{
					$content=$textnew;
				}
				$content=str_replace('\n','<BR>',$content);
				$content=str_replace('<AM><S1>','<BOLD>',$content);
				$content=str_replace('</S1></AM>','</BOLD>',$content);
				$content=str_replace('<AM><S2>','<BOLD>',$content);
				$content=str_replace('</S2></AM>','</BOLD>',$content);
				$content=str_replace('<AM><S3>','<CB>',$content);
				$content=str_replace('</S3></AM>','</CB>',$content);
				$content=str_replace('<BR></CB>','</CB><BR>',$content);
				$content=str_replace('<AR>','',$content);
				$content=str_replace('</AR>','',$content);
			}else{
				if($p['print_top']){
					$content = "<AM><S1>".$p['print_top']."\n</S1></AM>";
					$content .=$text;
				}else{
					$content=$text;
				}
			}
			$printparams=array('sendcontent'=>$content,'id'=>$p['printerid']);
			if($p['print_type'] == 1 || $daike || ($p['print_type']==2 && ($order['ispay'] || $order['status']==1))){//付款后打印/货到付款			
				if($p['type']==7){
					$this->plugin('jy_feieyun')->printer($printparams,'jy_weishop',true,$p['print_nums']);
				}elseif($p['type']==8){
					model('jy_xpyun/model')->sendprint($printparams['id'],$printparams['sendcontent'],true,$p['print_nums']);
				}else{
					$this->plugin('jy_print')->printer($printparams,'jy_weishop',true,$p['print_nums']);
				}
			}
			return true;
	}
	public function sendNotice($params)
	{
		$tag = ((isset($params['tag']) ? $params['tag'] : ''));
		$touser = ((isset($params['openid']) ? $params['openid'] : ''));
		if (empty($touser)) {
			return;
		}
	}
	public function strlen_pad($str,$alllen)//补齐空格
	{
		//真实字符串长度（一个中文=2）
		$len = (strlen($str)+mb_strlen($str,'UTF-8'))/2;
		$buqi = '';
		for($i=0;$i<($alllen-$len);$i++){
			$buqi .= ' ';
		}
		$new_str = $str.$buqi;
		return $new_str;
	}
}
